import 'package:craze/common/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

class ChooseView extends StatefulWidget {
  const ChooseView({super.key});

  @override
  State<ChooseView> createState() => _ChooseViewState();
}

class _ChooseViewState extends State<ChooseView> {
  // 返回路径
  String? _returnPath;
  // 是否保留导航栈
  bool _preserveNavStack = false;

  @override
  void initState() {
    super.initState();
    // 延迟获取参数，确保GoRouter已完全初始化
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getReturnPath();
    });
  }

  // 获取返回路径
  void _getReturnPath() {
    final state = GoRouterState.of(context);
    // 从LoginDialog传递过来的返回路径参数
    _returnPath = state.uri.queryParameters['returnPath'];
    // 获取是否保留导航栈的参数
    _preserveNavStack = state.uri.queryParameters['preserveNavStack'] == 'true';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: 1.sw,
        height: 1.sh,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.startBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Stack(
            children: [
              // 返回按钮
              Positioned(
                top: 10.h,
                left: 20.w,
                child: GestureDetector(
                  onTap: () => GoRouter.of(context).pop(),
                  child: Icon(
                    MyIcons.iconBack,
                    color: MyColors.white,
                    size: 24.sp,
                  ),
                ),
              ),

              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // App logo
                  SizedBox(height: 0.15.sh),
                  Container(
                    width: 84.w,
                    height: 84.w,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(MyImages.logo),
                        fit: BoxFit.cover,
                      ),
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                  ),

                  SizedBox(height: 10.h),

                  // App name
                  Text(
                    'Craze',
                    style: TextStyle(
                      color: MyColors.white,
                      fontSize: 34.sp,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      fontWeight: FontWeight.bold,
                    ),
                  ),

                  const Spacer(),

                  // Login button
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 24.w),
                    child: GestureDetector(
                      onTap: () => _navigateToLogin(),
                      child: Container(
                        height: 58.h,
                        decoration: BoxDecoration(
                          color: MyColors.blue,
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(
                            color: MyColors.white.withAlpha(100),
                            width: 1.w,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              MyIcons.iconLock,
                              color: MyColors.white,
                              size: 26.sp,
                            ),
                            SizedBox(width: 8.w),
                            Text(
                              'Existing User Login',
                              style: TextStyle(
                                fontSize: 14.sp,
                                fontWeight: FontWeight.bold,
                                fontFamily:
                                    GoogleFonts.mochiyPopOne().fontFamily,
                                color: MyColors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  // Apple login button
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 24.w),
                    child: GestureDetector(
                      onTap: () async {
                        // Apple 登录注册并自动登录
                        try {
                          final credential =
                              await SignInWithApple.getAppleIDCredential(
                                scopes: [
                                  AppleIDAuthorizationScopes.email,
                                  AppleIDAuthorizationScopes.fullName,
                                ],
                              );
                          final username =
                              credential.email ??
                              credential.userIdentifier ??
                              'apple_${DateTime.now().millisecondsSinceEpoch}';
                          final password = '123456';
                          final authStore = getIt<AuthStore>();
                          final success = await authStore.register(
                            username: username,
                            password: password,
                            name: "User",
                            email: credential.email ?? '',
                          );
                          if (success) {
                            await authStore.login(username, password);
                            MyToast.showSuccess(context, 'Login successful');
                            GoRouter.of(context).go(AppRouter.home);
                          } else {
                            MyToast.showError(
                              context,
                              authStore.errorMessage ?? 'Apple login failed',
                            );
                          }
                        } catch (e) {
                          MyToast.showError(
                            context,
                            'Apple login failed: \n$e',
                          );
                        }
                      },
                      child: Container(
                        height: 58.h,
                        decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(
                            color: MyColors.white.withAlpha(100),
                            width: 1.w,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.apple,
                              color: MyColors.white,
                              size: 28.sp,
                            ),
                            SizedBox(width: 8.w),
                            Text(
                              'Continue with Apple',
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.bold,
                                color: MyColors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  SizedBox(height: 20.h),

                  // Register link
                  GestureDetector(
                    onTap: () => _navigateToRegister(),
                    child: Text(
                      'Register',
                      style: TextStyle(
                        color: MyColors.white.withAlpha(150),
                        fontSize: 15.sp,
                        fontWeight: FontWeight.w400,
                        fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      ),
                    ),
                  ),

                  SizedBox(height: 55.h),

                  // Terms and privacy policy
                  Padding(
                    padding: EdgeInsets.only(bottom: 40.h),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          'By Continuing you agree with ',
                          style: TextStyle(
                            color: MyColors.white.withAlpha(200),
                            fontSize: 12.sp,
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            WangYe.openUrl(
                              'https://www.freeprivacypolicy.com/live/6ee5cfdb-37a7-43f6-8e15-d7d1c6f445dd',
                            );
                          },
                          child: Text(
                            'Terms of Service',
                            style: TextStyle(
                              color: MyColors.white.withAlpha(200),
                              fontSize: 12.sp,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),
                        Text(
                          ' & ',
                          style: TextStyle(
                            color: MyColors.white.withAlpha(200),
                            fontSize: 12.sp,
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            WangYe.openUrl(
                              'https://www.freeprivacypolicy.com/live/e6e0f319-b2c8-4d57-8f03-1c7cc833be3c',
                            );
                          },
                          child: Text(
                            'Privacy Policy',
                            style: TextStyle(
                              color: MyColors.white.withAlpha(200),
                              fontSize: 12.sp,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 导航到登录页面，并传递返回路径
  void _navigateToLogin() {
    if (_returnPath != null && _returnPath!.isNotEmpty) {
      context.pushNamed(
        'login',
        queryParameters: {
          'returnPath': _returnPath,
          'fromPage': 'choose',
          'preserveNavStack': _preserveNavStack.toString(),
        },
      );
    } else {
      context.push('/login');
    }
  }

  // 导航到注册页面，并传递返回路径
  void _navigateToRegister() {
    if (_returnPath != null && _returnPath!.isNotEmpty) {
      context.pushNamed(
        'register',
        queryParameters: {'returnPath': _returnPath},
      );
    } else {
      context.push('/register');
    }
  }
}
